<template>
  <view class="container">
    <!-- 基本信息部分 -->
    <view class="info-section">
      <view class="section-title">基础信息</view>
      <view class="section-content">
        <view class="form-item">
          <text>单号:</text>
          <input type="text" v-model="orderNumber" placeholder="请输入单号" class="input-gray-rounded" />
        </view>
        <view class="form-item">
          <text>入库日期:</text>
          <picker mode="date" value="2024-10-1" @change="handleDateChange">
            <view class="input">{{ outDate }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text>供应商:</text>
          <picker mode="selector" :range="suppliers" @change="handleSupplierChange">
            <view class="input">{{ selectedSupplier }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text>仓库:</text>
          <picker mode="selector" :range="warehouses" @change="handleWarehouseChange">
            <view class="input">{{ selectedWarehouse }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text>备注:</text>
          <input type="text" v-model="remark" placeholder="请输入备注" class="input-gray-rounded" />
        </view>
      </view>
    </view>

    <!-- 选择商品和扫码增加按钮部分 -->
    <view class="product-section">
      <button class="action-button" @click="Goods">选择商品</button>
      <button class="action-button">扫码增加</button>
    </view>

    <!-- 选择的商品信息列表部分 -->
    <scroll-view class="product-list" scroll-y>
		<view v-if="products.length === 0" style='display: flex;flex-direction: column;align-items: center;margin-top: 50px;'>
		  <image src='../../Resources/Image/空空如也.png' style='width: 120px;height:120px;margin-bottom: 10px;'></image>
		  <br>
		  <div><span style="font-size: 20px; font-weight: bold; color: #b3b3b3">暂未需要入库的商品</span></div>
		</view>
      <view class="product-item" v-for="(item, index) in products" :key="index">
        <image class="product-image" src="../../static/logo.png" /> <!-- 替换为实际商品图片路径 -->
        <view class="product-info">
          <view class="product-name">{{item.goods_name}}</view>
          <view class="product-quantity">数量: {{ item.goods_count }}</view>
          <view class="product-price">￥{{ item.goods_sum_price }}</view>
        </view>
      </view>
    </scroll-view>

    <!-- 总金额和总数量以及确认入库按钮部分 -->
    <view class="total-section">
      <view class="total-amount">总金额: ¥{{ totalAmount }}</view>
      <view class="total-quantity">总数量: {{ totalQuantity }}</view>
      <button class="confirm-button" @click="confirmInbound">确认入库</button>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { GoodsStore } from '../../Store/GoodsStore';
import { TokenStore } from '../../Store/TokenStore';
import { config } from '../../config';
import { WareHouseStore } from '../../Store/WareHouseStore';
import { LoginState } from '../../util/LoginSate';

const outDate = ref('2024-10-1');
const orderNumber = ref('');
const AllSuppliers = ref([])//供应商总文件夹
const suppliers = ref();//存放供应商姓名
const selectedSupplier = ref("请选择供应商");
const warehouses = ref([]);//单存放名称
const ArrWareHouse = ref([]);//存放整体仓库对象
const selectedWarehouse = ref("请选择仓库");
const remark = ref('');
const products = ref([
]);
const totalAmount = ref(0);
const totalQuantity = ref(0);

let ButtonState = ref(true);

let pageinfo= ref({
	size:100,
	page:1
})

onMounted(()=>{
	if(!LoginState()){
		uni.showToast({
		  title: '登录失效',
		  icon: 'error'
		});
		uni.redirectTo({
			url:"/pages/index/index"
		})
		return ;
	}
	AllProduct()
	AllSupplier()
	AllWareHouse()
	orderNumber.value = generateOrderNumber();
})

//从pinia中获取已选择的订单数据
function AllProduct(){
	let data = GoodsStore().goods;
	console.log("从pinia中取出"+data);
	if(data!=''){
		ButtonState.value = false;
	}
	else {
		ButtonState.value = true;
	}
	console.log("从pinia中获取："+data);
	if(data!=''){
		products.value = JSON.parse(data);
		//清空pinia释放线程
		GoodsStore().renew();
		//计算数量统计数据
		for(let i=0;i<products.value.length;i++){
			totalQuantity.value+=products.value[i].goods_count;
		}
		//计算金额统计数据
		for(let i=0;i<products.value.length;i++){
			totalAmount.value+=products.value[i].goods_sum_price;
		}
		
		console.log("统计数据："+totalQuantity.value);
		console.log("统计金额:"+totalAmount.value)
	}
	else {
		console.log("当前未选择数据")
	}
}

//从后端获取供应商信息
function AllSupplier(){
	uni.request({
		url:`${config.baseURL}/Supplier/AllSuppliers`,
		method:'POST',
		data:pageinfo.value,
		header: {
		  'content-type': 'application/json', // 设置请求头为 JSON
		  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
		},
		success:(res)=>{
			if(res.data.data === 'error'){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
			else {
				let data = JSON.parse(res.data.data);
				
				AllSuppliers.value = data.filter(supplier => supplier.supplier_status  === "合作中");
				
				console.log("获取有效供应商："+JSON.stringify(AllSuppliers.value))
				
				suppliers.value = AllSuppliers.value.map(item => item.supplier_name);
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
}

//从后端获取仓库数据
function AllWareHouse(){
	uni.request({
		url:`${config.baseURL}/Warehouse/AllWH`,
		method:'POST',
		data:pageinfo.value,
		header: {
		  'content-type': 'application/json', // 设置请求头为 JSON
		  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
		},
		success:(res)=>{
			if(res.data.data === 'error'){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
			else {
				console.log("获取仓库信息成功"+res.data.data);
				let data = JSON.parse(res.data.data)
				ArrWareHouse.value = data
				warehouses.value = data.map(item => item.warehouse_name);
				console.log("获取到仓库"+JSON.stringify(ArrWareHouse.value))
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
}

//随机生成订单号工具方法
function generateOrderNumber() {
  // 获取当前时间的时间戳（以毫秒为单位）
  const timestamp = Date.now();

  // 将时间戳转换为字符串并截取中间的八位数字
  const timestampStr = timestamp.toString().slice(-8);

  // 生成一个随机的八位数字字符串
  const randomStr = Math.random().toString(36).slice(2, 10).toUpperCase();

  // 组合订单号
  const orderNumber = `SN${timestampStr}${randomStr}`;

  return orderNumber;
}


function handleDateChange(e) {
  outDate.value = e.detail.value;
}

function handleSupplierChange(e) {
  selectedSupplier.value = suppliers.value[e.detail.value];
}

function handleWarehouseChange(e) {
  selectedWarehouse.value = warehouses.value[e.detail.value];
  let warehouse = ArrWareHouse.value.find(w => w.warehouse_name === selectedWarehouse.value);
   WareHouseStore().setwarehouse(JSON.stringify(warehouse));
  console.log("仓库信息存入pinia"+JSON.stringify(warehouse));
}

function confirmInbound() {
  // 确认入库的逻辑
  console.log('入库日期:', outDate.value);
  console.log('单号:', orderNumber.value);
  console.log('供应商:', selectedSupplier.value);
  console.log('仓库:', selectedWarehouse.value);
  console.log('备注:', remark.value);
  // 将数据发送到后端...
  
  if(selectedSupplier.value === '请选择供应商' || selectedWarehouse.value === '请选择仓库' || remark.value === ''){
	  uni.showToast({
	    title: "请填写所有字段",
	    icon: 'error'
	  });
	  return ;
  }
  
  if(products.value.length === 0){
	  uni.showToast({
	    title: "请选择商品",
	    icon: 'error'
	  });
	  return ;
  }
  
  let Outsuplier = AllSuppliers.value.filter(supplier => supplier.supplier_name === selectedSupplier.value);
  
  let warehouse_id = ArrWareHouse.value.filter(warehouse => warehouse.warehouse_name === selectedWarehouse.value)
  
  console.log("所选仓库id："+JSON.stringify(warehouse_id[0].id))
  
  //向后端发送的数据
  let OnBounds = {
	  order_sn:orderNumber.value,
	  warehouse_id:warehouse_id[0].id,
	  supplier:Outsuplier,
	  goods:products.value,
	  purchase_amount:totalAmount.value,
	  purchase_type:"1",
	  purchase_date:outDate.value,
	  pay_type:"Y",
	  remark:remark.value
  }
  
  let diaContent = "您于"+outDate.value+"从供应商"+selectedSupplier.value+"采购进货至仓库"+selectedWarehouse.value+"订单号为："+orderNumber.value+"，总金额为："+totalAmount.value+"。如有错误请联系开发者";
  
  uni.showModal({
  		title: "信息确认",
  		content: diaContent,
  		showCancel:true,
  		success: function (res) {
  			if (res.confirm) {
  				console.log('用户点击确定');
				console.log("向后端发送："+JSON.stringify(OnBounds))
  				//----------------------------------向后端发送数据---------------------------------
				uni.request({
					url:`${config.baseURL}/OnBound/On`,
					method:'POST',
					data:OnBounds,
					header: {
					  'content-type': 'application/json', // 设置请求头为 JSON
					  'Authorization': TokenStore().token // 确保 TokenStore 函数已定义
					},
					success:(res)=>{
						if(res.data.data === '1'){
							uni.showToast({
							  title: "入库成功",
							  icon: 'suucess'
							});
						}
						else if(res.data.data === 'error'){
							uni.showToast({
							  title: "数据库错误",
							  icon: 'error'
							});
						}
					},
					fail:(err)=>{
						uni.showToast({
						  title: err.errMsg,
						  icon: 'error'
						});
					}
				})
  				//------------------------------------------------------------------------------
  			} else if (res.cancel) {
  				console.log('用户点击取消');
  			}
  		},
  		fail:function (err){
  			comsole.log("出发错误事件")
  		}
  	});
  
  
  
}

function Goods(){
	console.log("从pinia中取出"+GoodsStore().goods)
	if(!ButtonState.value){
		uni.showToast({
		  title: "已经有一个进程在运行了，请返回上一级继续操作",
		  icon: 'none'
		});
		return null;
	}
  uni.navigateTo({
    url:'/pages/InGoods/InGoods'
  })
}
</script>

<style scoped>
/* 样式代码，根据您的需求进一步美化 */
.container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f8f8f8;
}

.product-list {
/*  margin: 10px 0; */
  background-color: #fff;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-height: 300px; /* 固定高度 /
overflow-y: auto; / 可滑动 */
  width: 95%;
}

.info-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.section-content {
  margin-top: 15px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input {
  flex-grow: 1;
  margin-left: 10px;
  border: 1px solid #ddd;
  padding: 8px 12px;
  border-radius: 4px;
}

.input-gray-rounded {
  flex-grow: 1;
  margin-left: 10px;
  border: 1px solid #ccc; /* 灰色边框 */
  padding: 8px 12px;
  border-radius: 5px; /* 圆角边框 */
  background-color: #fafafa; /* 背景色 */
}

.input-gray-rounded:focus {
  border-color: #3b82f6; /* 聚焦时边框颜色 */
}

.product-section {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  border: none;
  font-size: 17px;
  border-radius: 5px;
  background-color: #3b82f6;
  color: white;
  margin: 0 10px;
  cursor: pointer;
  height: 40px;
}

.product-list {
  height: 270px; /* 根据需要调整高度 */
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  border-radius: 5px;
}

.product-info {
  flex-grow: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.product-quantity, .product-price {
  font-size: 14px;
  color: #666;
}

.total-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.total-amount, .total-quantity {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.confirm-button {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 5px;
  background-color: #3b82f6;
  color: white;
  font-size: 16px;
  cursor: pointer;
}
</style>
